package com.stuffthathappens.concurrency;

import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.BlockingQueue;

/**
 * @author Eric Burke
 */
public class DonutConsumer implements Runnable {
    private final String name;
    private final BlockingQueue<Donut> queue;
    private final TimeUnit delayUnit;
    private final long delay;
    private volatile int numAte = 0;

    public DonutConsumer(String name, BlockingQueue<Donut> queue,
                         TimeUnit delayUnit, long delay) {
        this.name = name;
        this.queue = queue;
        this.delayUnit = delayUnit;
        this.delay = delay;
    }

    public void run() {

        try {
            while (true) {
                // block until a new donut is available
                Donut d = queue.take();

                System.out.format("* The queue contains %d donuts.%n", queue.size());

                System.out.format(":-)  %s eats a %s %s donut!%n",
                        name, d.getProducerName(), d.getType());

                numAte++;

                // pause between donuts
                delayUnit.sleep(delay);
            }
        } catch (InterruptedException e) {
            // let this Runnable die
            System.out.println(name + " is interrupted.");
        }
    }

    public int getNumAte() {
        return numAte;
    }

    public String getName() {
        return name;
    }
}
